package yxy.game.pm2.command.wuchao;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.WuchaoMessage;
import yxy.game.pm2.module.wuchao.WuchaoHandle;
import yxy.game.pm2.module.wuchao.WuchaoModule;
import yxy.game.pm2.module.wuchao.event.WuchaoEvent;
import yxy.game.pm2.module.wuchao.event.WuchaoEventEnemy;

/** 乌巢 乌巢毒药 */
@MessageType(proto = Command.WuchaoPoison, classtype = WuchaoMessage.WuchaoPoisonRequest.class)
public class CMD_WuchaoPoison extends Command<WuchaoMessage.WuchaoPoisonRequest> {

	@Override
	public void execute(MessageSource messageSource, WuchaoMessage.WuchaoPoisonRequest request) {
		String playerCode = messageSource.getTag();
		String eventCode = request.getCode();

		WuchaoMessage.WuchaoPoisonResponse.Builder response = WuchaoMessage.WuchaoPoisonResponse.newBuilder();

		WuchaoModule wuchaoModule = WuchaoModule.get(playerCode);
		if (wuchaoModule.getStage() <= 0) {
			send(messageSource, response, Result.WuchaoNotStart);// 没有开始挑战
			return;
		}
		if (wuchaoModule.getPoison() <= 0) {
			send(messageSource, response, Result.WuchaoPoisonOver);// 毒药没了
			return;
		}
		try {
			if (wuchaoModule.tryLock()) {
				WuchaoEvent event = wuchaoModule.getEvents().get(eventCode);

				if (event == null || event.isOver()) {
					send(messageSource, response, Result.WuchaoPoisonDead);// 事件不可用
					return;
				}
				if (!(event instanceof WuchaoEventEnemy)) {
					send(messageSource, response, Result.ParamError);// 事件不可用
					return;
				}

				new WuchaoHandle().killEnemy(playerCode, wuchaoModule, (WuchaoEventEnemy) event);
				wuchaoModule.setPoison(wuchaoModule.getPoison() - 1);
				wuchaoModule.set();

				response.setCode(event.getCode());
				response.setPoison(wuchaoModule.getPoison());

				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			wuchaoModule.unlock();
		}
	}

	private void send(MessageSource messageSource, WuchaoMessage.WuchaoPoisonResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}